package cn.lmxdev.ptms.service.impl;

import cn.lmxdev.ptms.bean.exception.BizException;
import cn.lmxdev.ptms.bean.table.TUserRole;
import cn.lmxdev.ptms.dao.IUserRoleDao;
import cn.lmxdev.ptms.service.IUserRoleServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
public class UserRoleServletImpl implements IUserRoleServlet {
    private final IUserRoleDao userRoleDao;

    @Autowired
    public UserRoleServletImpl(
            IUserRoleDao userRoleDao
    ) {
        this.userRoleDao = userRoleDao;
    }

    @Override
    @Transactional
    public TUserRole get(Long id) {
        return this.userRoleDao.find(id);
    }

    @Override
    @Transactional
    public long add(TUserRole userRole) {
        // 判断名称是否已经存在
        TUserRole userRoleByName = this.userRoleDao.findByName(userRole.getName());
        if (userRoleByName != null && userRoleByName.getId() > 0)
            throw new BizException("操作失败，该名称已经存在");

        // 判断角色是否已经存在
        TUserRole userRoleByRole = this.userRoleDao.findByRole(userRole.getRole());
        if (userRoleByRole != null && userRoleByRole.getId() > 0)
            throw new BizException("操作失败，该角色已经存在");

        // 插入数据
        if (!this.userRoleDao.insert(userRole))
            throw new BizException("操作失败");

        // 返回ID
        return userRole.getId();
    }

    @Override
    @Transactional
    public void remove(Long id) {
        // 删除数据
        if (!this.userRoleDao.delete(id))
            throw new BizException("操作失败");
    }

    @Override
    @Transactional
    public void edit(TUserRole userRole) {
        // 查询旧数据
        TUserRole oldUserRole = this.userRoleDao.find(userRole.getId());

        // 判断名称是否已经存在
        TUserRole userRoleByName = this.userRoleDao.findByName(userRole.getName());
        if (userRoleByName != null && !Objects.equals(userRoleByName.getId(), oldUserRole.getId()))
            throw new BizException("操作失败，该名称已经存在");

        // 判断角色是否已经存在
        TUserRole userRoleByRole = this.userRoleDao.findByRole(userRole.getRole());
        if (userRoleByRole != null && !Objects.equals(userRoleByRole.getId(), oldUserRole.getId()))
            throw new BizException("操作失败，该角色已经存在");

        // 更新属性
        oldUserRole.setName(userRole.getName())
                .setRole(userRole.getRole());

        // 保存数据
        if (!this.userRoleDao.update(oldUserRole))
            throw new BizException("操作失败");
    }

    @Override
    @Transactional
    public long count(TUserRole userRole) {
        return this.userRoleDao.count(userRole);
    }

    @Override
    @Transactional
    public List<TUserRole> list(Long limit, Long page, TUserRole userRole) {
        return this.userRoleDao.select(page != null ? (page - 1) * limit : null, limit, userRole);
    }
}
